package com.five.api.controller;


import com.alibaba.fastjson.JSONObject;
import com.five.api.service.ArticleService;
import com.five.api.service.CollectionService;
import com.five.controller.BaseController;
import com.five.entity.Article;
import com.five.entity.ArticleLabel;
import com.five.entity.User;
import com.five.entity.qo.ArticleQo;
import com.five.entity.qo.UsersAndArticles;
import com.five.qo.ArticleCommentQO;
import com.five.vo.BaseResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 博客文章表 前端控制器
 * </p>
 *
 * @author star
 * @since 2021-06-16
 */
@RestController
@CrossOrigin(allowCredentials = "true",originPatterns = "*")
@RequestMapping("article")
@Api("文章业务接口")
public class ArticleController extends BaseController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CollectionService collectionService;

    @GetMapping("getArticleDetail")
    @ResponseBody
    @ApiOperation("获取文章详情信息")
    public BaseResultVO getArticleDetail(Long id) {
        Article articleDetail = articleService.getArticleDetail(id);
        return successResp(articleDetail);
    }

    @ResponseBody
    @RequestMapping(value = "info", method = RequestMethod.GET)
    @ApiOperation("查询文章信息")
    public BaseResultVO selectArticle(Long page, ArticleQo articleQo) {
        System.out.println(page);
        System.out.println(articleQo.getArticleTypeId());
        System.out.println(articleQo.getArticleDescribe());
        List articles = articleService.selectArticleByPage(page,articleQo);
        return successResp(articles);
//        List articles = articleService.selectArticleList();
//        return successResp(articles);

    }

    @ResponseBody
    @RequestMapping(value = "sum", method = RequestMethod.GET)
    @ApiOperation("文章总和接口")
    public BaseResultVO sumForArticle() {

        UsersAndArticles usersAndArticles = articleService.selectArticleToSum();
        return successResp(usersAndArticles);
    }


    @ApiOperation("根据用户id查询文章接口")
    @PostMapping("selectArticleByUserId")
    public BaseResultVO selectArticleByUserId(@ApiParam("用户id") @RequestParam("userId") Long userId){
        if (userId == null || userId == 0){
            return errorResp("用户id不能为空");
        }
        List<ArticleCommentQO> articles = articleService.selectArticleByUserId(userId);
        return successResp(articles);
    }

    @ApiOperation("删除文章接口")
    @PostMapping("deleteArticle")
    public BaseResultVO deleteArticle(@ApiParam("文章id") @RequestParam("id") Long id){
        if (id == null || id == 0){
            return errorResp("用户id不能为空");
        }
        int i = articleService.deleteArticle(id);
        if (i == 0 ){
            return errorResp("删除文章失败");
        }
        return successResp("删除成功");
    }




    //博客图片上传问题
    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        //上传路径保存设置

        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
        String path = "/usr/local/nginx/html/view/upload/";



        //按照月份进行分类：
        Calendar instance = Calendar.getInstance();
        String month = (instance.get(Calendar.MONTH) + 1)+"mouth";
        path = path+month;

        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdirs();
        }

        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        //解决文件名字问题：我们使用uuid;
        String filename = "pg-"+ UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
        File newfile = new File(realPath, filename);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newfile);

        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url","/view/upload/"+month+"/"+ filename);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }

    @ResponseBody
    @RequestMapping(value = "addArticle",method = RequestMethod.POST)
    @ApiOperation("新增文章接口")
    public BaseResultVO addArticle(Article article, @RequestParam("labelsStr") String labels){

        System.out.println(article+"-------------");
        System.out.println(labels+"-------------");
        articleService.addArticle(article, labels);

        return successResp("添加成功");
    }

    @PostMapping("updateArticle")
    @ResponseBody
    @ApiOperation("更新文章详情信息")
    public BaseResultVO updateArticle(Article article){
        articleService.updateArticle(article,true);
        return successRespWithMessage("更新文章信息成功");
    }

    @PostMapping("collectArticle")
    @ResponseBody
    @ApiOperation("收藏文章")
    public BaseResultVO collectArticle(Article article){

        User sessionUser = (User) SecurityUtils.getSubject().getPrincipal();
        if(sessionUser == null){
            return errorResp("你还未登录无法收藏文章！");
        }

        Boolean isCollection = collectionService.checkIsCollection(sessionUser.getId(), article.getId());
        //文章已收藏
        if(isCollection){
            BaseResultVO resultVO = new BaseResultVO();
            resultVO.setCode(BaseResultVO.Code.IS_COLLECTION.getValue());
            resultVO.setMessage("文章已收藏，是否取消收藏？");
            return resultVO;
        }
        //文章未收藏
        //跟新文章收藏数量
        articleService.updateArticle(article,true);
        //收藏文章
        collectionService.insertCollection(sessionUser.getId(),article.getId());
        return successRespWithMessage("收藏文章成功");
    }

    @PostMapping("cancelCollect")
    @ResponseBody
    @ApiOperation("收藏文章")
    public BaseResultVO cancelCollect(Article article){

        User sessionUser = (User) SecurityUtils.getSubject().getPrincipal();
        if(sessionUser == null){
            return errorResp("登录超时，请重新登录");
        }


        //跟新文章收藏数量
        articleService.updateArticle(article,false);
        //收藏文章
        collectionService.deleteCollection(sessionUser.getId(),article.getId());
        return successRespWithMessage("取消收藏成功");
    }

    @PostMapping("updateArticleDetail")
    @ApiOperation("修改文章详细信息接口")
    public BaseResultVO updateArticleDetail(@ApiParam("文章对象") ArticleQo article,@RequestParam("articleLabel") String articleLabel){
        if (article == null){
            return errorResp("修改的文章不能为空");
        }

        System.out.println("修改文章：");
        System.out.println(article);
        System.out.println(articleLabel);
        articleService.updateArticleDetail(article,articleLabel);

        return successResp("修改成功");
    }
}
